<template lang="jade">
	div(v-loading="loading")
		div(class="container")
			<product-type-form v-model="productType"></product-type-form>
		div(class="container " v-if="productType.id")
			div(class="alert alert-warning") 
				strong 注意！
				span 删除产品属性或属性值，对应的产品sku可能会被删除，删除请谨慎
		div(class="product-type-property-container")
			div(class="container")

				div(class="row")
						div(class="col-md-6")
							property-list(v-model="productType.properties",
								@selected="change_editing_property")
						div(class="col-md-6")
							property-form(v-model="property",@save="add_property")
</template>
<script>
	import _ from 'lodash';
	import PropertyForm from './property-form';
	import PropertyList from './property-list';
	import ProductTypeForm from  './product-type-form'

	import Property from '../models/_property';
	import PropertyItem from '../models/property-item';
	import ProductType from '../models/product-type';
	import Axios from 'axios';

	export default{
		data(){
			return{
				productType: new ProductType(),
				property: new Property(),
				loading:false
			}
		},
		components:{
			'property-form': PropertyForm,
			'property-list': PropertyList,
			'product-type-form': ProductTypeForm
		},
		methods:{
			add_property: function(val){
				this.productType.addProperty(val);
				this.property = new Property();
			},
			change_editing_property: function(property){
				this.property = property;
			},
			get_product_type_editing(id){
				this.loading=true;
				var vm = this;
				Axios.get('/api/services/app/productTypeQs/GetProductType',{
					params:{typeId:id}
				}).then((res)=>{
					var data = res.data.result;
					var propertyGroups = _.groupBy(data.elements, (element)=>{return element.propertyId});

					var properties = [];
					_.each(propertyGroups,(group)=>{
						var property = new Property();
						property.name = group[0].propertyName;
						property.id = group[0].propertyId;
						property.items = _.map(group, (item)=> {
							var propertyItem = new PropertyItem();
							propertyItem.name = item.propertyItemName;
							propertyItem.id = item.propertyItemId;
							return propertyItem;
						});
						properties.push(property);
					});
					data.properties = properties;
					vm.productType = data;
					vm.loading=false;
				});
			}
		},
		mounted(){
			if( this.$route.params.id) 
				this.get_product_type_editing(this.$route.params.id);
		}
	}
</script>
